<script setup lang="tsx">
import { onMounted, reactive } from 'vue'
import { ElButton } from 'element-plus'
import { DynamicForm } from '@/components/DynamicForm'
import type { FormSchema } from '@/components/DynamicForm'
import { useForm } from '@/hooks/useForm'
import { useValidator } from '@/hooks/useValidator'

const { required } = useValidator()
const {
  formRegister,
  formMethods: { setSchema, getFormData, setValues, getElFormExpose }
} = useForm()
// 模拟远程加载
const getTreeSelectData = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        {
          label: 'option1',
          value: '1'
        },
        {
          label: 'option2',
          value: '2'
        }
      ])
    }, 3000)
  })
}

const schema = reactive<FormSchema[]>([
  {
    field: 'field',
    label: 'input',
    component: 'Input',
    componentProps: {
      clearable: true,
      slots: {
        suffix: () => <>美元</>
      }
    },
    value: 1
  },
  {
    field: 'field2',
    label: 'select',
    component: 'Select',
    componentProps: {
      on: {
        change: (val: string | number) => {
          setSchema([{ field: 'field3', path: 'remove', value: val !== '1' }])
        }
      }
    },
    optionApi: async () => {
      const res = await getTreeSelectData()
      return res
    },
    value: '1'
  },
  {
    field: 'field3',
    label: 'input2',
    component: 'Input',
    remove: false
  },
  {
    field: 'field4',
    label: 'input3',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  }
])

const getData = async () => {
  const result = await getFormData()
  console.log('result', result)
}

const reset = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.resetFields()
}

const formValidation = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.validate((isValid) => {
    console.log(isValid)
  })
}

onMounted(() => {
  setValues({
    field: 1,
    field2: '1',
    field3: 2
  })
})
</script>

<template>
  <DynamicForm :schema="schema" labelWidth="60" label-position="left" @register="formRegister" />
  <ElButton type="primary" @click="getData">获取表单数据</ElButton>
  <ElButton @click="reset">重置表单数据</ElButton>
  <ElButton @click="formValidation">验证表单</ElButton>
</template>

<style scoped></style>
